<script lang="ts" setup>
import { isDark } from '@/utils/is'
import { useAppStore } from '@/store/modules/app'
import { useDesign } from '@/hooks/web/useDesign'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import routerSearch from '@/components/RouterSearch/index.vue'
import { qiankunWindow } from 'vite-plugin-qiankun/es/helper'
import { useMessageSubject } from './utils/sub-rxjs-util'
import { BatchTabMessage, MessageBodyInfo, TabMessage } from './wap'
import { CommonQianKunEnum } from './utils/constants'

defineOptions({ name: 'APP' })

const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('app')
const appStore = useAppStore()
const currentSize = computed(() => appStore.getCurrentSize)
const greyMode = computed(() => appStore.getGreyMode)
const { wsCache } = useCache()
const prefix = wsCache.get(CommonQianKunEnum.BASER_ROUTE_PREFIX)
const POWERED_BY_QIANKUN = qiankunWindow.__POWERED_BY_QIANKUN__;
const cachedComponents = ref<string[]>([]);
const wrapperCache = new Map<string, any>();
// 组件生命周期日志
function logLifecycle(name: string) {
  onMounted(() => {
    console.log(`%c${name} mounted`, 'color:green');
  });
  onUnmounted(() => {
    wrapperCache.delete(name);
    console.log(`%c${name} unmounted`, 'color:green');
  });
  onActivated(() => {
    console.log(`Component ${name} activated`);
  })
  onDeactivated(() => {
    console.log(`Component ${name} deactivated`);
  })
}
function wrap(component, route) {
  const wrapperName = decodeURI(route.fullPath);

  // 如果路由不属于当前子应用，返回 null
  if (wrapperName && !wrapperName.startsWith(prefix)) {
    return null;
  }

  // 如果组件已经缓存，直接返回
  if (wrapperCache.has(wrapperName)) {
    return wrapperCache.get(wrapperName);
  }

  // 创建新的组件并缓存
  const wrapper = defineComponent({
    name: wrapperName,
    setup() {
      logLifecycle(wrapperName);
      return () => h(component);
    },
  });

  wrapperCache.set(wrapperName, wrapper);
  // 将组件名称添加到 cachedComponents 列表
  if (!cachedComponents.value.includes(wrapperName)) {
    cachedComponents.value = [...cachedComponents.value, wrapperName] 
  }
  return wrapper;
}
if (POWERED_BY_QIANKUN) {
  useMessageSubject()?.subscribe({
    next: (body: MessageBodyInfo) => {
      if (body.operation === 'closePortalTab') {
        const message = body.message as TabMessage;
        const targetUrl = decodeURI(message.targetUrl);
        // 直接从 cachedComponents 列表中移除目标组件
        cachedComponents.value = cachedComponents.value.filter((url) => url !== targetUrl);
      } else if (body.operation === 'batchClosePortalTab') {
        const message = body.message as BatchTabMessage;
        message.targetUrlList.forEach((item) => {
          const targetUrl = decodeURI(item);
          // 直接从 cachedComponents 列表中移除目标组件
          cachedComponents.value = cachedComponents.value.filter((url) => url !== targetUrl);
        });
      }
    },
  });
}
// 根据浏览器当前主题设置系统主题色
// const setDefaultTheme = () => {
//   let isDarkTheme = wsCache.get(CACHE_KEY.IS_DARK)
//   if (isDarkTheme === null) {
//     isDarkTheme = isDark()
//   }
//   appStore.setIsDark(isDarkTheme)
// }
// setDefaultTheme()
</script>
<template>
  <!-- <ConfigGlobal :size="currentSize"> -->
  <RouterView v-if="!POWERED_BY_QIANKUN" :class="greyMode ? `${prefixCls}-grey-mode` : ''" />
  <router-view v-slot="{ Component, route }" v-if="POWERED_BY_QIANKUN">
    <keep-alive :include="cachedComponents" >
      <component :is="wrap(Component, route)" :key="decodeURI(route.fullPath)" />
    </keep-alive>
  </router-view>
  <!-- <routerSearch /> -->
  <!-- </ConfigGlobal> -->
</template>
<style lang="scss">
$prefix-cls: #{$namespace}-app;

.size {
  width: 100%;
  height: 100%;
}

html,
body {
  @extend .size;

  padding: 0 !important;
  margin: 0;
  overflow: hidden;

  #app {
    @extend .size;
  }
}

.#{$prefix-cls}-grey-mode {
  filter: grayscale(100%);
}

.scrollbar__view {
  height: 99% !important;
}

/**覆盖portal默认给子应用的z-index=0导致的子应用弹窗遮罩层级太低 */
.sh3h-wap-portal-antdv-layout-content {
  z-index: 200 !important;
}
</style>
